package com.imooc.mall.service.impl;

import com.imooc.mall.dao.UserMapper;
import com.imooc.mall.pojo.User;
import com.imooc.mall.service.UserService;
import com.imooc.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

import static com.imooc.mall.enums.ResponseEnum.*;
import static com.imooc.mall.enums.RoleEnum.CUSTOMER;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseVo<User> register(User user) {
//        error();

        int count = userMapper.countByUsername(user.getUsername());
        if (count > 0) {
            return ResponseVo.error(USERNAME_EXIST);
        }
        int count1 = userMapper.countByEmail(user.getEmail());
        if (count1 > 0) {
            return ResponseVo.error(EMAIL_EXIST);
        }

        user.setRole(CUSTOMER.getCode());
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        int i = userMapper.insertSelective(user);
        if (i == 0) {
            return ResponseVo.error(ERROR);
        }

        return ResponseVo.success();
    }

    private void error() {
        throw new RuntimeException("测试异常捕捉器，统一返回结果的形式");
    }



    @Override
    public ResponseVo<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);

        if (!DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)).equalsIgnoreCase(user.getPassword())) {
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        user.setPassword("");
        return ResponseVo.success(user);
    }


}
